package com.gxc.datacore.ws.util;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;

import com.gxc.datacore.ws.domain.RequestInfo;
import com.gxc.datacore.ws.domain.ResponseInfo;
import com.gxc.webcore.util.StringUtil;

public class XmlUtil {

	/**
	 * 构建requestXml
	 * 
	 * @param requestInfo
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static String buildRequestXml(RequestInfo requestInfo) {
		Document doc = DocumentHelper.createDocument();
		Element root = doc.addElement("requestXml");
		root.addElement("id").addText(
				requestInfo.getId() == null ? StringUtil.getUUID()
						: requestInfo.getId());
		root.addElement("username").addText(
				requestInfo.getUsername() == null ? "" : requestInfo
						.getUsername());
		root.addElement("password").addText(
				requestInfo.getPassword() == null ? "" : requestInfo
						.getPassword());
		root.addElement("object_id").addText(
				requestInfo.getObject_id() == null ? "" : requestInfo
						.getObject_id());
		// 查询参数
		Element paramsElement = root.addElement("params");
		Map params = requestInfo.getParams();
		String keyString = null;
		String valueString = null;
		if (params != null && params.size() > 0) {
			for (Object key : params.keySet()) {
				if (!StringUtil.isTrimEmpty((String) key)) {
					keyString = ((String) key).trim();
					valueString = params.get(key) == null ? ""
							: (String) params.get(key);
					paramsElement.addElement(keyString).addText(valueString);
				}
			}
		}
		// 请求时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm-ss");
		root.addElement("request_time").addText(
				requestInfo.getRequest_time() == null ? sdf.format(new Date())
						: sdf.format(requestInfo.getRequest_time()));
		return doc.asXML();
	}

	/**
	 * 解析requestXml
	 * 
	 * @param requestXml
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static RequestInfo parseRequestXml(String requestXml)
			throws Exception {
		RequestInfo requestInfo = new RequestInfo();
		String xpath = null;
		Element element = null;
		Document doc = DocumentHelper.parseText(requestXml);
		xpath = "//requestXml/id";
		element = (Element) doc.selectSingleNode(xpath);
		requestInfo.setId(element == null ? StringUtil.getUUID() : element
				.getTextTrim());
		xpath = "//requestXml/username";
		element = (Element) doc.selectSingleNode(xpath);
		requestInfo.setUsername(element == null ? null : element.getTextTrim());
		xpath = "//requestXml/password";
		element = (Element) doc.selectSingleNode(xpath);
		requestInfo.setPassword(element == null ? null : element.getTextTrim());
		xpath = "//requestXml/object_id";
		element = (Element) doc.selectSingleNode(xpath);
		requestInfo
				.setObject_id(element == null ? null : element.getTextTrim());
		// 查询参数
		xpath = "//requestXml/params";
		element = (Element) doc.selectSingleNode(xpath);
		Map params = new HashMap();
		for (Iterator it = element.elementIterator(); it.hasNext();) {
			Element item = (Element) it.next();
			params.put(item.getName(), item.getTextTrim());
		}
		requestInfo.setParams(params);
		// 请求时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm-ss");
		xpath = "//requestXml/request_time";
		element = (Element) doc.selectSingleNode(xpath);
		if (element != null) {
			try {
				requestInfo.setRequest_time(sdf.parse(element.getTextTrim()));
			} catch (Exception e) {
				requestInfo.setRequest_time(new Date());
				e.printStackTrace();
			}
		} else {
			requestInfo.setRequest_time(new Date());
		}
		return requestInfo;
	}

	/**
	 * 构建responseInfo
	 * 
	 * @param responseInfo
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static String buildResponseXml(ResponseInfo responseInfo) {
		Document doc = DocumentHelper.createDocument();
		Element root = doc.addElement("responseXml");
		root.addElement("id").addText(
				responseInfo.getId() == null ? StringUtil.getUUID()
						: responseInfo.getId());
		root.addElement("request_id").addText(
				responseInfo.getRequest_id() == null ? "" : responseInfo
						.getRequest_id());
		root.addElement("status_code").addText(
				responseInfo.getStatus_code() == null ? "" : responseInfo
						.getStatus_code());
		root.addElement("status_name").addText(
				responseInfo.getStatus_name() == null ? "" : responseInfo
						.getStatus_name());
		// 响应结果
		Element resultElement = root.addElement("result");
		Element rowsElement = resultElement.addElement("rows");
		if (responseInfo.getResult() != null) {
			String keyString = null;
			String valueString = null;
			for (int i = 0; i < responseInfo.getResult().size(); i++) {
				Map row = (Map) responseInfo.getResult().get(i);
				Element rowElement = rowsElement.addElement("row");
				for (Object key : row.keySet()) {
					if (!StringUtil.isTrimEmpty((String) key)) {
						keyString = ((String) key).trim();
						valueString = row.get(key) == null ? "" : (String) row
								.get(key);
						rowElement.addElement(keyString).addText(valueString);
					}
				}
			}
		}
		// 响应时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm-ss");
		root.addElement("request_time").addText(
				responseInfo.getResponse_time() == null ? sdf
						.format(new Date()) : sdf.format(responseInfo
						.getResponse_time()));
		return doc.asXML();
	}

	/**
	 * 解析responseXml
	 * 
	 * @param responseXml
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static ResponseInfo parseResponseXml(String responseXml)
			throws Exception {
		ResponseInfo responseInfo = new ResponseInfo();
		String xpath = null;
		Element element = null;
		Document doc = DocumentHelper.parseText(responseXml);
		xpath = "//responseXml/id";
		element = (Element) doc.selectSingleNode(xpath);
		responseInfo.setId(element == null ? StringUtil.getUUID() : element
				.getTextTrim());
		xpath = "//responseXml/request_id";
		element = (Element) doc.selectSingleNode(xpath);
		responseInfo
				.setRequest_id(element == null ? "" : element.getTextTrim());
		xpath = "//responseXml/status_code";
		element = (Element) doc.selectSingleNode(xpath);
		responseInfo.setStatus_code(element == null ? "" : element
				.getTextTrim());
		xpath = "//responseXml/status_name";
		element = (Element) doc.selectSingleNode(xpath);
		responseInfo.setStatus_name(element == null ? "" : element
				.getTextTrim());
		// 相应结果
		xpath = "//responseXml/result/rows/row";
		List<Node> nodeList = doc.selectNodes(xpath);
		if (nodeList != null && nodeList.size() > 0) {
			List resultList = new ArrayList();
			for (Node node : nodeList) {
				Map row = new HashMap();
				element = (Element) node;
				for (Iterator it = element.elementIterator(); it.hasNext();) {
					Element item = (Element) it.next();
					row.put(item.getName(), item.getTextTrim());
				}
				resultList.add(row);
			}
			responseInfo.setResult(resultList);
		}
		// 相应时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm-ss");
		xpath = "//responseXml/response_time";
		element = (Element) doc.selectSingleNode(xpath);
		if (element != null) {
			try {
				responseInfo.setResponse_time(sdf.parse(element.getTextTrim()));
			} catch (Exception e) {
				responseInfo.setResponse_time(new Date());
				e.printStackTrace();
			}
		} else {
			responseInfo.setResponse_time(new Date());
		}

		return null;
	}

}
